package org.fastsyncer.sdk.client;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.apache.http.message.BasicNameValuePair;
import org.fastsyncer.common.entity.RestResult;
import org.fastsyncer.common.util.JsonUtil;
import org.fastsyncer.common.util.SHA1Util;
import org.fastsyncer.sdk.client.http.HttpConnector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class AbstractClient implements Client, Oauth {

	private static final Logger logger = LoggerFactory.getLogger(AbstractClient.class);

	/**
	 * 访问凭据标识
	 */
	private static final String TOKEN = "token";

	/**
	 * 获取凭据标识URL
	 */
	private static final String TOKEN_URL = "/oauth";

	private String ip = "127.0.0.1";

	private int port = 18686;

	private String username = "admin";

	private String userpwd = SHA1Util.b64_sha1("admin");

	// 数据同步服务地址
	private String serviceUrl = "http://${ip}:${port}/rest";

	// 服务端凭据
	private String token;

	// 默认使用Http连接器
	private Connector connector = new HttpConnector();

	protected void init() throws IllegalArgumentException {
		init(ip, port, username, userpwd);
	}

	protected void init(String ip, int port, String username, String userpwd) throws IllegalArgumentException {
		this.ip = ip;
		this.port = port;
		this.username = username;
		this.userpwd = SHA1Util.b64_sha1(userpwd);
		// http://127.0.0.1:18686/rest
		serviceUrl = serviceUrl.replace("${ip}", ip).replace("${port}", String.valueOf(port));
		// 获取服务器Token
		refreshToken();
	}

	@Override
	public void close() throws IOException {
		if (null == connector) {
			connector.close();
		}
	}

	private String send(String url, List<BasicNameValuePair> params) {
		// http://${ip}:${port}/rest/start?token=836391306&id=123
		String msg = connector.send(serviceUrl.concat(url), params);
		// 将消息转换为Object
		RestResult r = JsonUtil.jsonToObj(msg, RestResult.class);
		if (null == r) {
			return null;
		}
		// 检查请求是否成功,值可能是JSON格式
		Object vObj = r.getResultValue();
		String v = null == vObj ? null : String.valueOf(vObj);
		if (!r.isSuccess()) {
			logger.error(v);
			// 如果是认证失败
			if(401 == r.getStatus()){
				logger.info("正在尝试重新认证..");
				// 获取服务器Token
				refreshToken();
			}
			return null;
		}
		return JsonUtil.jsonToString(v);
	}

	@Override
	public void refreshToken() throws IllegalArgumentException {
		String r = send(TOKEN_URL, Arrays.asList(new BasicNameValuePair("username", username),
				new BasicNameValuePair("userpwd", userpwd)));
		if (StringUtils.isBlank(r)) {
			throw new IllegalArgumentException("Authentication failure.");
		}
		token = r;
	}

	@Override
	public String sendWithToken(String url, List<BasicNameValuePair> params) {
		if (null == params) {
			params = new ArrayList<>();
		}
		params.add(new BasicNameValuePair(TOKEN, token));
		return send(url, params);
	}

	public String getIp() {
		return ip;
	}

	public int getPort() {
		return port;
	}

}
